<?php
/**
 * Created by PhpStorm.
 * User: xufei
 * Date: 2018/5/4
 * Time: 上午10:19
 */

class wxapi_ctl_user extends wxapi_response
{
    public $pagedata;

    public function __construct(&$app)
    {        
        parent::__construct($app);
        $this->app = app::get('b2c');
    }

    public function pointInfo()
    {
        $page = $_GET['page'] ? $_GET['page'] : 1;
        $size = $_GET['size'] ? $_GET['size'] : 10;
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        $pointModel = app::get('b2c')->model('member_point');
        $pointList = array();
        $pointList = $pointModel->getList('*',array('member_id'=>$member['member_id']), $page, $size);
        $totalCount = count($pointList);

        $api_data = array(
            'userPoint' => $member['point'],
            'code' => '0',
            'page_total' => ceil($totalCount/$size),
            'pageSize' => $size,
            'list' => $pointList,
            'totalCount' => $totalCount,
            'pageNum' => $page,
        );

        self::return_json($api_data);
    }

    public function signin(){
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $site_checkout_login_point_open = app::get('b2c')->getConf('site.checkout.login_point.open');
        $site_login_point_num = app::get('b2c')->getConf('site.login_point.num');
        if($site_checkout_login_point_open == 'false')
        {
            $return = [
                'result' => '未开启签到送积分功能',
                'code' =>  5001,
            ];
            return self::return_json($return);
        }

        $signin_obj = app::get('b2c')->model('member_signin');
        $member_id = $member['member_id'];
        $signin_date = date('Y-m-d');

        if($signin_obj->exists_signin($member_id,$signin_date))
        {
            $return = [
                'result' => '您今天已经签到过',
                'code' =>  5001,
                'status' => 0
            ];
            return self::return_json($return);
        }
        $data = array(
            'member_id' => $member_id,
            'signin_date' => $signin_date,
            'signin_time' => time(),
            'point' => $site_login_point_num
        );
        $result = kernel::single('b2c_member_signin')->sign($data);
        if($result){
            $msg = '签到成功，获得'.$site_login_point_num.'积分';
            $return = [
                'result' => $msg,
                'code' =>  0,
                'status' => 1
            ];
            return self::return_json($return);
        }else{
            $return = [
                'result' => '签到失败',
                'code' =>  5001,
                'status' => 0
            ];
            return self::return_json($return);
        }
    }

    public function signInfo(){
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        $pointDetail = $this->getPointDetail();
        $signin_obj = app::get('b2c')->model('member_signin');
        $member_id = $member['member_id'];
        $signin_date = date('Y-m-d');

        if($signin_obj->exists_signin($member_id,$signin_date))
        {
            $return = [
                'result' => '您今天已经签到过',
                'has_signed' => 1,
                'code' =>  0,
                'pointDetail' => $pointDetail,
            ];
            return self::return_json($return);
        } else {
            $return = [
                'result' => '今天未签到',
                'has_signed' => 0,
                'code' =>  0,
                'pointDetail' => $pointDetail,
            ];
            return self::return_json($return);
        }
    }

    /**
     * 获取最近七天签到情况
     */
    public function getSignDate()
    {
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $signin_obj = app::get('b2c')->model('member_signin');
        $where['member_id'] = $member['member_id'];
        $where['signin_time|between'] = array(strtotime(date("Y-m-d", strtotime("-1 week"))), time());
        $signList = $signin_obj->getList('*', $where);
        //获取积分
        $memberPoint = app::get('b2c')->model('member_point');
        $pointList = $memberPoint->getList('*', array('member_id'=>$member['member_id']),0,10,'id desc');
        $return = [
            'result' => '',
            'signList' => $signList,
            'pointList' => $pointList,
            'code' =>  0,
        ];
        return self::return_json($return);
    }

    public function getMyOrderList()
    {
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $orderStatus = trim($_GET['orderStatus']);
        $receiveFlg = intval($_GET['receiveFlg']); //2:待收货订单类型 4:已完成订单类型
        $page = intval($_GET['page']);
        if( !$page) $page = 1;
        $size = intval($_GET['size']);
        if( !$size) $size = 10;
        $type = intval($_GET['type']);// 0:"全部订单", 1:"待支付", 2:"待收货",3:"已完成"
        $orderModel = app::get('b2c')->model('orders');
        $order_status = array();
        $filters = array();
        switch ($type) {
            case '1': //未支付  //未发货
                $order_status['promotion_type'] = 'normal';
                $order_status['pay_status'] = 0;
                $order_status['status'] = 'active';
                $order_status['ship_status'] = 0;
                break;
                
            case '2':
                //已支付   //已发货
                $order_status['pay_status'] = 1;
                $order_status['status'] = 'active';
                $order_status['ship_status'] = array(0,2);
                $filters['received_status'] = 0;
                break;
                
            case '3':
                //已支付   //已发货
                $order_status['promotion_type'] = 'normal';
                $order_status['pay_status'] = 1;
                $order_status['status'] = 'active';
                $order_status['ship_status'] = 1;
                $filters['received_status'] = 0;
                break;
                
            case '4':
                $order_status['status'] = 'finish'; //已完成
                break;
        }
        switch ($receiveFlg) {
            case '2': //待收货订单类型
                $order_status['pay_status'] = 1;
                $order_status['ship_status'] = 1;
                break;
            case '4': //已完成订单类型
                $order_status['status'] = 'finish';
                break;
        }
        $totalCount = 0;
        $aData = $orderModel->fetchByMember($member['member_id'],$page, $order_status,$size, $filters);
        
        $this->__get_order_details($aData,'member_orders');
        $order_status['member_id'] = $member['member_id'];
        $totalCount = $orderModel->count($order_status);
        $return = array(
            "result" => "0",
            "reason" => "",
            "code"=> 0 ,
            "page_total" => $page,
            "pageSize" => $size,
            "list" => [],
            "totalCount" => 0,
            "pageNum" => 0
        );
        if(empty($aData['data'])){
            return self::return_json($return);
        }

        //self::return_json($aData);
        $order_list = array();
        foreach ($aData['data'] as $keys => $order){
            $itemList = [];
            
            //处理订单赠品
            if($order['gift_items']){
                foreach($order['gift_items'] as $gift_items){
                    $order['goods_items'][] = array(
                        'product' => $gift_items
                    );
                }                
            }
            
            foreach ($order['goods_items'] as $key=>$goods_items){
                
                $tmp_goods = array($goods_items);
                
                //处理商品的赠品
                if($goods_items['gift_items']){
                    foreach($goods_items['gift_items'] as $gift_items){
                        $tmp_goods[] = array(
                            'product' => $gift_items
                        );
                    }
                }
                
                foreach($tmp_goods as $goods){
                    $item = array(
                        'auditStatus' => 1,
                        'evaluateStatus' => 0, //评价状态
                        'goodsId' => $goods['product']['goods_id'],
                        'goodsSkuId' => $goods['product']['item_id'],
                        'goodsName' => $goods['product']['name'],
                        'orderNo' => $goods['product']['order_id'],
                        'id' => $goods['product']['item_id'],
                        'num' => $goods['product']['quantity'],
                        'price' => number_format($goods['product']['price'],2),
                        'refundStatus' => 0, //0:正常,1:待审核,2:退款中,3:退款完成
                    );
                    $item['goodsLogo'] = base_storager::image_path($goods['product']['thumbnail_pic']);
                    $item['goodsThumLogo'] = base_storager::image_path($goods['product']['thumbnail_pic']);
                    $addonArrs = '';
                    if( !empty($goods['product']['addon']) ){
                        $addon = unserialize($goods['product']['addon']);
                        if($addon['product_attr']){
                            $i = 1;
                            foreach ($addon['product_attr'] as $val){
                                $addonArrs .= $val['label'].":".$val['value'];
                                if (count($addon['product_attr']) != $i){
                                    $addonArrs .= "、";
                                }
                                $i ++;
                            }
                        }
                        $addonArrs = "[".$addonArrs."]";
                    }
                    $item['goodsSkuVals']  = $addonArrs;
                    $itemList[] = $item;
                }
            }
            
            //物流处理
            $deliveryModel = app::get('b2c')->model('delivery');
            $shipOrder = $deliveryModel->getRow('*', array('order_id'=>$order['order_id']));
            //$obj_return_policy = kernel::service("aftersales.return_policy");
            //(!isset($obj_return_policy) || !is_object($obj_return_policy)) ? $is_obj_return_policy =0 : $is_obj_return_policy=1;
            //$is_aftersales = $obj_return_policy->is_order_aftersales($order['order_id'],$member['member_id']);
            //$is_aftersales = $this->__is_order_aftersales($order, $member['member_id']);
            
            //订单操作按钮
            $btnStatus = array(
                'pay' => '0',
                'cancel' => '0',
                'aftersale' => '0',
                'refund' => '0',
                'confirm' => '0',
            );            
            $statusName = $this->_process_status($order, $btnStatus);
            //是否售后的状态
            //$aftersaleData = $this->__is_order_aftersales($order['order_id'],$member['member_id']);
            //$btnStatus['aftersale'] = $aftersaleData['status'];
            $order_list[] = array(
                'auditStatus' => 0,
                'businessAccount' => '',    //店铺
                'businessId' => '',         //店铺id
                'businessName' => '',       //店铺id
                'createTime' => date('Y-m-d H:i:s',$order['createtime']),
                'deliverStatus' => $order['ship_status'], //发货状态：0未发货，1已发货，2部分发货，3部分退货，4已退货
                'freight' => $order['shipping']['cost_shipping'], //运费
                'goodsPrices' => number_format($order['total_amount'], 2), //商品总额
                'id' => $order['order_id'],
                'logisticsCode' => $shipOrder['logi_id'], //物流公司编码
                'logisticsNo' => $shipOrder['logi_no'], //物流单号
                'orderItemList' => $itemList,
                'orderNo' => $order['order_id'],
                "payStatus" => $order['pay_status'], //是否支付(0 未支付 1 已支付(或拼团成功) 2 处理中 3 部分付款 4 部分退款 5 全额退款) ,6付款成功，拼团没完成,7.拼团退款中,8拼团.等待退款
                "payTradeNo" => '', //支付单号
                "status" => $order['status'], //active:活动, dead:死单, finish:完成, pending:暂停
                "totalPrice" => $order['cur_amount'], //应付总额
                "statusName" => $statusName, //状态名称
                "btnStatus" => $btnStatus, //操作按钮状态
                "received_status" => $order['received_status'],
            );
        }
        
        $return = array(
            'result' => '0',
            'reason' => '',
            'code' => 0,
            'page_total' => ceil($totalCount/$size),
            'page_size' => $size,
            'list' => $order_list,
            'totalCount' => $totalCount,
            'pageNum' => $page,
        );
        return self::return_json($return);
    }

    /**
     *查询我的订单数量
     */

    public function getMyOrderSize()
    {
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $finishCount = 0;
        $orderModel = app::get('b2c')->model('orders');
        //查询代付款订单
        $pendingPayWhere = array();
        $pendingPayWhere['member_id'] = $member['member_id'];
        $pendingPayWhere['promotion_type'] = 'normal';
        $pendingPayWhere['pay_status'] = 0;
        $pendingPayWhere['status'] = 'active';
        $pendingPayWhere['ship_status'] = 0;
        $pendingPayCount = $orderModel->count($pendingPayWhere);
        //查询待发货订单
        $backrdersWhere = array();
        $backrdersWhere['member_id'] = $member['member_id'];
        $backrdersWhere['promotion_type'] = 'normal';
        $backrdersWhere['pay_status'] = 1;
        $backrdersWhere['status'] = 'active';
        $backrdersWhere['ship_status'] = 1;
        $backrdersWhere['received_status'] = 0;
        $backrdersCount = $orderModel->count($backrdersWhere);
        //查询已完成
        $filter = array(
            'status' => 'active',
            'pay_status' => '1',
            'ship_status' => array(0,2),
            'member_id' => $member['member_id'],
        );
        $waitShipNum = $orderModel->count($filter);

        $return = [
            'result' => 0,
            'code' => 0,
            'pendingPayCount' => intval($pendingPayCount), //待付款
            'backrdersCount' => intval($backrdersCount), //待发货
            'waitShipNum' => intval($waitShipNum) ,//已完成
        ];
        return self::return_json($return);
    }

    /**
     * 根据订单号查询详情
     */
    public function getOrderDetail()
    {
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            return self::api_error('请先登录');
        }
        $member_id = $member['member_id'];
        $order_id = trim($_GET['orderNo']);
        if( ! $order_id ){
            return self::api_error('订单号错误');
        }

        $objOrder = app::get('b2c')->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))), 'order_pmt'=>array('*'));
        $sdf_order = $objOrder->dump($order_id, '*', $subsdf);
        if( ! $sdf_order){
            return self::api_error('订单不存在');
        }
        
        if($member['member_id']!=$sdf_order['member_id']){
            return self::api_error('没有权限查看该订单');
        }

        // 处理收货人地区
        $arr_consignee_area = array();
        $arr_consignee_regions = array();
        if (strpos($sdf_order['consignee']['area'], ':') !== false)
        {
            $arr_consignee_area = explode(':', $sdf_order['consignee']['area']);
            if ($arr_consignee_area[1])
            {
                if (strpos($arr_consignee_area[1], '/') !== false)
                {
                    $arr_consignee_regions = explode('/', $arr_consignee_area[1]);
                }
            }

            $sdf_order['consignee']['area'] = (is_array($arr_consignee_regions) && $arr_consignee_regions) ? $arr_consignee_regions[0] . $arr_consignee_regions[1] . $arr_consignee_regions[2] : $sdf_order['consignee']['area'];
        }

        // 订单的相关信息的修改
        $obj_other_info = kernel::servicelist('b2c.order_other_infomation');
        if ($obj_other_info){
            foreach ($obj_other_info as $obj){
                $this->pagedata['discount_html'] = $obj->gen_point_discount($sdf_order);
            }
        }
        
        $order_payed = kernel::single('b2c_order_pay')->check_payed($sdf_order['order_id']);
        if($order_payed==$sdf_order['total_amount']){
            $sdf_order['is_pay'] = 1;
        }else{
            $sdf_order['is_pay'] = 0;
        }
        //判断预售 promotion_type
        if($sdf_order['promotion_type']=='prepare'){
            $prepare_order=kernel::service('prepare_order');
            if($prepare_order)
            {
                $prepare=$prepare_order->get_order_info($sdf_order['order_id']);
                $order_payed = kernel::single('b2c_order_pay')->check_payed($sdf_order['order_id']);
                if($order_payed>0 ){
                    if( $prepare['begin_time'] < time() && time() < $prepare['end_time'] ){
                        if($order_payed==$prepare['preparesell_price']){
                            $sdf_order['is_pay']=1;
                        }
                    }
                }
            }
        }
        //显示是否有必填项
        $minfo = $objOrder->minfo($sdf_order);
        if(!empty($minfo)){
            $this->pagedata['is_minfo'] = 1;
            $this->pagedata['minfo'] = $minfo;
        }else{
            $this->pagedata['is_minfo'] = 0;
        }

        $order_items = array();
        $gift_items = array();
        $this->__get_order_detail_item($sdf_order,'member_order_detail');
        $this->pagedata['order'] = $sdf_order;
        /** 将商品促销单独剥离出来 **/
        if ($this->pagedata['order']['order_pmt'])
        {
            foreach ($this->pagedata['order']['order_pmt'] as $key=>$arr_pmt)
            {
                if ($arr_pmt['pmt_type'] == 'goods')
                {
                    $this->pagedata['order']['goods_pmt'][$arr_pmt['product_id']][$key] =  $this->pagedata['order']['order_pmt'][$key];
                    unset($this->pagedata['order']['order_pmt'][$key]);
                }
            }
        }
        /** end **/

        // 得到订单留言.
        $oMsg = kernel::single("b2c_message_order");
        $arrOrderMsg = $oMsg->getList('*', array('order_id' => $order_id, 'object_type' => 'order'), $offset=0, $limit=-1, 'time DESC');

        $this->pagedata['ordermsg'] = $arrOrderMsg;
        $this->pagedata['res_url'] = $this->app->res_url;

        //我已付款
        $timeHours = array();
        for($i=0;$i<24;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeHours[$v] = $v;
        }
        $timeMins = array();
        for($i=0;$i<60;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeMins[$v] = $v;
        }
        $this->pagedata['timeHours'] = $timeHours;
        $this->pagedata['timeMins'] = $timeMins;

        // 生成订单日志明细
        $arr_order_logs = $objOrder->getOrderLogList($order_id);
        $this->pagedata['orderlogs'] = $arr_order_logs['data'];
        $logi = app::get('logisticstrack')->is_actived();
        $this->pagedata['logi'] = $logi;

        // 取到支付单信息
        $obj_payments = app::get('ectools')->model('payments');
        $this->pagedata['paymentlists'] = $obj_payments->get_payments_by_order_id($order_id);

        // 支付方式的解析变化
        $obj_payments_cfgs = app::get('ectools')->model('payment_cfgs');
        $arr_payments_cfg = $obj_payments_cfgs->getPaymentInfo($this->pagedata['order']['payinfo']['pay_app_id']);
        $this->pagedata['order']['payment'] = $arr_payments_cfg;
        
        //处理商品缩略图
        $goodsImg = array();
        foreach ($sdf_order['gift_items'] as $v){
            $goodsImg[$v['goods_id']] = $v['thumbnail_pic'];
        }
        foreach ($sdf_order['goods_items'] as $goods){
            $goodsImg[$goods['product']['goods_id']] = $goods['product']['thumbnail_pic'];
            foreach($goods['gift_items'] as $v){
                $goodsImg[$v['goods_id']] = $v['thumbnail_pic'];
            }            
        }
        
        $orderItem = array();
        //self::return_json($sdf_order['order_objects']);
        foreach ($sdf_order['order_objects'] as $key=>$goods){
            foreach ($goods['order_items'] as $item){
                $addonArrs = '';
                if( !empty($item['addon']) ){
                    $addon = unserialize($item['addon']);
                    if($addon['product_attr']){
                        $i = 1;
                        foreach ($addon['product_attr'] as $val){
                            $addonArrs .= $val['label'].":".$val['value'];
                            if (count($addon['product_attr']) != $i){
                                $addonArrs .= "、";
                            }
                            $i ++;
                        }
                    }
                    $addonArrs = "[".$addonArrs."]";
                }
                $orderItem[] = array(
                    'evaluateStatus' => 0, //评价状态
                    'goodsId' => $item['goods_id'],
                    'goodsName' => $item['name'],
                    'goodsSkuId' => '',
                    'goodsSkuVals' => $addonArrs,
                    'id' => $item['item_id'],
                    'num' => $item['quantity'],
                    'price' => number_format($item['price'], 2),
                    'refundStatus'=>0,
                    'item_id' =>  $item['item_id'],
                    'product_id' => $item['products']['product_id'],
                    'name' => $item['name'],
                    'num' => $item['quantity'],
                    'max_num' => $item['quantity'],
                    'price' => number_format($item['price'],2),
                    'refund_status' => '',
                    'goods_bn' => $item['bn'],
                    'big_pic' => base_storager::image_path($goodsImg[$item['goods_id']]),
                    'goodsThumLogo' => base_storager::image_path($goodsImg[$item['goods_id']]),
                    'addon' => $goods['addon'],
                );
            }
        }
        //物流处理
        $deliveryModel = app::get('b2c')->model('delivery');
        $shipOrder = $deliveryModel->getList('logi_no,logi_name', array('order_id'=>$sdf_order['order_id']));
        //$obj_return_policy = kernel::service("aftersales.return_policy");
        //(!isset($obj_return_policy) || !is_object($obj_return_policy)) ? $is_obj_return_policy =0 : $is_obj_return_policy=1;
        //$is_aftersales = $obj_return_policy->is_order_aftersales($sdf_order['order_id'],$member_id);
        
        //$is_aftersales = $this->__is_order_aftersales($sdf_order, $member_id);

        $orderPayLastTime = 0;
        if(!empty($this->pagedata['paymentlists'])){
            $orderPayLastTime = date('Y-m-d H:i:s',$this->pagedata['paymentlists'][count($this->pagedata['paymentlists'])-1]['t_payed']);
        }

        //如果是售后取订单详情
        $is_aftersale = intval($_GET['is_aftersale']);
        if( $is_aftersale == 1){
            $obj_return_policy = kernel::service("aftersales.return_policy");
            
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }
            
            $aftersales_quantity = $obj_return_policy->order_products_quantity($order_id);
            //self::return_json($aftersales_quantity);
            foreach ($orderItem as $k=>$v)
            {
                if( ! isset($aftersales_quantity[$v['product_id']]) or $aftersales_quantity[$v['product_id']]<=0 ){
                    unset($orderItem[$k]);
                } else {
                    $orderItem[$k]['max_num'] = intval($aftersales_quantity[$v['product_id']]);
                    $orderItem[$k]['num'] = $orderItem[$k]['max_num'];
                }
            }
        }
        
        //订单操作按钮
        $btnStatus = array(
            'pay' => '0',
            'cancel' => '0',
            'aftersale' => '0',
            'refund' => '0',
            'confirm' => '0',
        );            
        $statusName = $this->_process_status($sdf_order, $btnStatus); 

        $return = [
            'result' => '0',
            'reason' => '',
            'code' => 0,
            'obj' => [
                'btnStatus' => $btnStatus,
                'statusName' => $statusName,
                'businessId' => '',
                'businessMessage' => '',
                'businessName' => '',
                'createTime' => date('Y-m-d H:i:s',$sdf_order['createtime']),
                'deliverStatus' => $sdf_order['pay_status'], //发货状态：0未发货，1已发货，2部分发货，3部分退货，4已退货
                'freight' => number_format($sdf_order['shipping']['cost_shipping'],2), //运费
                'goodsPrices' => number_format($sdf_order['cost_item'], 2), //商品总额
                'invoiceDetail' => '',
                'invoiceFlag' => '',
                'invoiceType' => '',
                'orderItemList'=> array_values($orderItem),
                'orderNo' => $sdf_order['order_id'],
                'payStatus' => $sdf_order['pay_status'], //是否支付(0 未支付 1 已支付(或拼团成功) 2 处理中 3 部分付款 4 部分退款 5 全额退款) ,6付款成功，拼团没完成,7.拼团退款中,8拼团.等待退款
                'payTradeNo' => '',
                'receiverAddress' => $sdf_order['consignee']['addr'],
                'receiverName' => $sdf_order['consignee']['name'],
                'receiverPhone' => $sdf_order['consignee']['mobile'],
                'status' => $sdf_order['status'], //active:活动, dead:死单, finish:完成, pending:暂停
                'systemTime' => date('Y-m-d H:i:s', time()),
                'payedTime' => $orderPayLastTime,
                'totalPrice' => number_format($sdf_order['total_amount'], 2),
                'shipOrder' => $shipOrder, //物流单号
                'shipOrderNum' => count($shipOrder), //物流单号
                'pmtOrder' => number_format($sdf_order['pmt_order'], 2),    // 优惠金额
                'receivedStatus' => $sdf_order['received_status'],    // 优惠金额
                'isAftersales' => $is_aftersales,
                'orderChgpointmoney' => $sdf_order['order_chgpointmoney'] ? number_format($sdf_order['order_chgpointmoney'], 2) : 0,    // 优惠金额
            ],
        ];
        return self::return_json($return);
    }

    /**
     * 收货地址
     */
    public function receiver(){
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $objMem = app::get('b2c')->model('members');
        $receiverList = $objMem->getMemberAddr($member['member_id']);
        $return = [
            'result' => '',
            'data' => $receiverList,
            'code' =>  0,
        ];
        return self::return_json($return);
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string tpl
     * @return null
     */
    private function __get_order_details(&$aData,$tml='member_orders')
    {
        if (isset($aData['data']) && $aData['data'])
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }

            foreach ($aData['data'] as &$arr_data_item)
            {
                $this->__get_order_detail_item($arr_data_item,$tml);
            }
        }
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string 模版名称
     * @return null
     */
    private function __get_order_detail_item(&$arr_data_item,$tpl='member_order_detail')
    {
        if (isset($arr_data_item) && $arr_data_item)
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }


            $arr_data_item['goods_items'] = array();
            $obj_specification = app::get('b2c')->model('specification');
            $obj_spec_values = app::get('b2c')->model('spec_values');
            $obj_goods = app::get('b2c')->model('goods');
            $oImage = app::get('image')->model('image');
            if (isset($arr_data_item['order_objects']) && $arr_data_item['order_objects'])
            {
                foreach ($arr_data_item['order_objects'] as $k=>$arr_objects)
                {
                    $index = 0;
                    $index_adj = 0;
                    $index_gift = 0;
                    $image_set = app::get('image')->getConf('image.set');
                    if ($arr_objects['obj_type'] == 'goods')
                    {
                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            if (!$arr_items['products'])
                            {
                                $o = app::get('b2c')->model('order_items');
                                $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                            }

                            if ($arr_items['item_type'] == 'product')
                            {
                                if ($arr_data_item['goods_items'][$k]['product'])
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k]['product']['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $arr_items['quantity'];

                                $arr_data_item['goods_items'][$k]['product'] = $arr_items;
                                $arr_data_item['goods_items'][$k]['product']['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k]['product']['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k]['product']['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k]['product']['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k]['product']['quantity']);
                                $arr_data_item['goods_items'][$k]['product']['amount'] = $arr_items['amount'];
                                $arr_goods_list = $obj_goods->getList('image_default_id,spec_desc', array('goods_id' => $arr_items['goods_id']));

                                $arr_goods = $arr_goods_list[0];
                                // 获取货品关联第一张图片
                                $select_spec_private_value_id = reset($arr_items['products']['spec_desc']['spec_private_value_id']);
                                $spec_desc_goods = reset($arr_goods['spec_desc']);
                                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                                    $arr_goods['image_default_id'] = $default_product_image;
                                }else{
                                    if( !$arr_goods['image_default_id'] && !$oImage->getList("image_id",array('image_id'=>$arr_goods['image_default_id']))){
                                        $arr_goods['image_default_id'] = $image_set['S']['default_image'];
                                    }
                                }

                                $arr_data_item['goods_items'][$k]['product']['thumbnail_pic'] = $arr_goods['image_default_id'];
                                if ($arr_items['addon'])
                                {
                                    $arrAddon = $arr_addon = unserialize($arr_items['addon']);
                                    if ($arr_addon['product_attr'])
                                        unset($arr_addon['product_attr']);
                                    $arr_data_item['goods_items'][$k]['product']['minfo'] = $arr_addon;
                                }else{
                                    unset($arrAddon,$arr_addon);
                                }
                                if ($arrAddon['product_attr'])
                                {
                                    foreach ($arrAddon['product_attr'] as $arr_product_attr)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] .= $arr_product_attr['label'] . app::get('b2c')->_(":") . $arr_product_attr['value'] . app::get('b2c')->_(" ");
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k]['product']['attr']) && $arr_data_item['goods_items'][$k]['product']['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k]['product']['attr'], app::get('b2c')->_(" ")) !== false)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] = substr($arr_data_item['goods_items'][$k]['product']['attr'], 0, strrpos($arr_data_item['goods_items'][$k]['product']['attr'], app::get('b2c')->_(" ")));
                                    }
                                }
                            }
                            elseif ($arr_items['item_type'] == 'adjunct')
                            {
                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);


                                if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj])
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $arr_items['quantity'];

                                if (!$arrGoods['image_default_id'])
                                {
                                    $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                }
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj] = $arr_items;
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']);
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                //$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['link_url'] = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_product','act'=>'index','arg0'=>$arr_items['products']['product_id']));
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['amount'] = $arr_items['amount'];

                                if ($arr_items['addon'])
                                {
                                    $arr_addon = unserialize($arr_items['addon']);

                                    if ($arr_addon['product_attr'])
                                    {
                                        foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                        }
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")) !== false)
                                    {
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")));
                                    }
                                }

                                $index_adj++;
                            }
                            else
                            {
                                // product gift.
                                if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                                {
                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift])
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift] = $arr_items;
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['name'] = $arr_items['name'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['price'] = $arr_items['price'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity']);
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'])
                                    {
                                        if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                                $index_gift++;
                            }
                        }
                    }
                    else
                    {
                        if ($arr_objects['obj_type'] == 'gift')
                        {
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {
                                foreach ($arr_objects['order_items'] as $arr_items)
                                {
                                    if (!$arr_items['products'])
                                    {
                                        $o = $this->app->model('order_items');
                                        $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                        $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                                    }

                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if (!isset($arr_items['products']['product_id']) || !$arr_items['products']['product_id'])
                                        $arr_items['products']['product_id'] = $arr_items['goods_id'];

                                    if ($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']])
                                        $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }

                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['name'] = $arr_items['name'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['price'] = $arr_items['price'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['point'] = intval($arr_items['score']*$arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']);
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['nums'] = $arr_items['quantity'];
                                    //$arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['link_url'] = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_product','act'=>'index','arg0'=>$arr_items['products']['product_id']));
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] .= $arr_product_attr['label'] . (":") . $arr_product_attr['value'] . (" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr']) && $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'])
                                    {
                                        if (strpos($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], (" ")) !== false)
                                        {
                                            $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] = substr($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], 0, strrpos($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {

                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                $arr_data_item['extends_items'][] = $str_service_goods_type_obj->get_order_object($arr_objects, $arr_Goods,$tpl);
                            }
                        }
                    }
                }
            }

        }
    }
    private function get_current_member()
    {
        return self::user_auth();
    }

    /**
     * 获取用户优惠券列表
     */
    public function getCouponList()
    {
        $this->app = app::get('b2c');
        $member = $this->member_info;
        if( ! $member['member_id'] ){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $oCoupon = kernel::single('b2c_coupon_mem');
        $aData = $oCoupon->get_list_m($member['member_id']);

        if ($aData) {
            foreach ($aData as $k => &$item) {
                if ($item['coupons_info']['cpns_status'] !=1) {
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('此种优惠券已取消');
                    $aData[$k]['status'] = 0;
                    $item['time']['from_time'] = date('Y-m-d',$item['time']['from_time']);
                    $item['time']['to_time'] = date('Y-m-d',$item['time']['to_time']);
                    continue;
                }

                $member_lvs = explode(',',$item['time']['member_lv_ids']);
                if (!in_array($this->member['member_lv'],(array)$member_lvs)) {
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('本级别不准使用');
                    $aData[$k]['status'] = 1;
                    $item['time']['from_time'] = date('Y-m-d',$item['time']['from_time']);
                    $item['time']['to_time'] = date('Y-m-d',$item['time']['to_time']);
                    continue;
                }

                $curTime = time();
                if ($curTime>=$item['time']['from_time'] && $curTime<$item['time']['to_time']) {
                    if ($item['memc_used_times']<$this->app->getConf('coupon.mc.use_times')){
                        if ($item['coupons_info']['cpns_status']){
                            $aData[$k]['memc_status'] = app::get('b2c')->_('可使用');
                            $aData[$k]['status'] = 2;
                        }else{
                            $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券已作废');
                            $aData[$k]['status'] = 3;
                        }
                    }else{
                        $aData[$k]['coupons_info']['cpns_status'] = false;
                        if($item['disabled'] == 'busy'){
                            $aData[$k]['memc_status'] = app::get('b2c')->_('使用中');
                            $aData[$k]['status'] = 4;
                        }else{
                            $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券次数已用完');
                            $aData[$k]['status'] = 5;
                        }
                    }
                }else{
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('还未开始或已过期');
                    $aData[$k]['status'] = 6;
                }

                $item['time']['from_time'] = date('Y-m-d',$item['time']['from_time']);
                $item['time']['to_time'] = date('Y-m-d',$item['time']['to_time']);
            }
        }

        return self::return_json($aData);
    }

    /**
     * 获取用户积分详情
     */
    public function getPointDetail()
    {
        $member = $this->member_info;
        if( !($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $obj_member = app::get('pointprofessional')->model('members');
        $member_point = app::get('pointprofessional')->model('member_point');
        $pointDetail = [];

        $nodes_obj = app::get('b2c')->model('shop');
        $nodes = $nodes_obj->count(array('node_type'=>'ecos.taocrm','status'=>'bind'));
        if($nodes > 0){
            $getlog_params = array('member_id'=>$member['member_id']);
            $pointlog = kernel::single('b2c_member_point_contact_crm')->getPointLog($getlog_params);
            $pointDetail['total'] = $obj_member->get_real_point($member['member_id']);
            $pointDetail['historys'] = $pointlog['historys'];
        }else{
            $params['data'] = $member_point->get_all_list('*',array('member_id' => $member['member_id'],'status'=>'false'));
            $pointDetail['total'] = $obj_member->get_real_point($member['member_id'],'1');
            $pointDetail['historys'] = $params['data'];
        }
        
        //转换时间戳
        foreach($pointDetail['historys'] as &$v){
            $v['addtime'] = date('Y-m-d H:i', $v['addtime']);
        }
        
        return $pointDetail;
    }

    //售前申请退款操作
    public function do_refund_apply(){
        //默认不成功
        $arr_json_data = array(
            "success" => false,
        );
        $member = $this->get_current_member();
        //$member['member_id'] = 10;    //测试用户
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        $order_id = $_GET["order_id"];
        if (!$order_id){
            $return = [
                'result' => '订单id不存在',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        $refund_apply_reason = $_GET["refund_apply_reason"];
        if(!$refund_apply_reason){
            $return = [
                'result' => '请选择退款理由',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        
        //检查订单是否符合要求：未发货 已支付
        $mdl_order = app::get('b2c')->model('orders');
        $order_info = $mdl_order->dump(array("order_id"=>$order_id),"pay_status,ship_status,member_id,final_amount");
        if(empty($order_info)){
            $return = [
                'result' => '此订单不存在',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        
        if($order_info["cur_amount"] == 0){
            $return = [
                'result' => '0元订单不能申请退款',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        
        //是否有售后申请记录
        $mdl_aftersales_return_product = app::get('aftersales')->model('return_product');
        $rs_aftersales_return_product = $mdl_aftersales_return_product->dump(array("order_id"=>$order_id));
       
       //判断是否有未操作过的此订单的退款申请记录
        $mdl_b2c_refund_apply = app::get('b2c')->model('refund_apply');
        $rs_refund_apply = $mdl_b2c_refund_apply->dump(array("order_id"=>$order_id,"status"=>"0"));
        
        //满足已支付 未发货 没有售后退换货记录的 做售前退款操作
        if($order_info["pay_status"] == "1" && $order_info["ship_status"] == "0" && empty($rs_aftersales_return_product) && empty($rs_refund_apply)){
            $refund_apply_bn = date("YmdHis",time()).str_pad(rand(1,999),4,'0',STR_PAD_LEFT);
            $current_time = time();
            $request_arr = array(
                "order_id" => $order_id,
                "member_id" => $order_info["member_id"],
                "refund_apply_bn" => $refund_apply_bn,
                "refunds_reason" => $refund_apply_reason,
                "money" => $order_info["cur_amount"],
                "current_time" => $current_time,
            );
            //如绑定把退款申请单打到oms
            $obj_apiv = kernel::single('b2c_apiv_exchanges_request');
            $obj_apiv->rpc_caller_request($request_arr, 'orderrefund');
            //生成售前退款记录
            $insert_arr = array(
                "refund_apply_bn" => $refund_apply_bn,
                "order_id" => $order_id,
                "member_id" => $order_info["member_id"],
                "money" => $order_info["cur_amount"],
                "refunds_reason" => $refund_apply_reason,
                "create_time" => $current_time,
                "last_modified" => $current_time,
            );
            if($mdl_b2c_refund_apply->insert($insert_arr)){
                //更新订单支付状态为退款申请中
                $mdl_order->update(array('pay_status'=>'6'),array('order_id'=>$order_id));
                $msg = '退款申请成功';
                $return = [
                    'result' => $msg,
                    'code' => 0,
                    'success' => 'true',
                ];
            }else{
                $msg = '退款申请失败';
                $return = [
                    'result' => $msg,
                    'code' => 0,
                    'success' => 'false',
                ];
            }
            $mdl_b2c_refund_apply->saveOrderLog($refund_apply_bn,$msg);
            return self::return_json($return);

        }else{
            $return = [
                'result' => '不满足退款条件',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
    }

    //积分兑换优惠券 兑换操作
    public function exchange()
    {
        $cpnsId = $_GET["cpns_id"];
        $arr_json_data = array("success"=>false);
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        //积分设置的用途
        $site_point_usage = app::get('b2c')->getConf('site.point_usage');

        if($site_point_usage != '1'){
            $return = [
                'result' => '积分只用于抵扣，不能兑换',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        if(!$cpnsId){
            $return = [
                'result' => '参数错误',
                'code' => 5001,
            ];
            return self::return_json($return);
        }
        $oExchangeCoupon = kernel::single('b2c_coupon_mem');
        $memberId = $member['member_id'];//会员id号
        $cur_coupon_nums = app::get('b2c')->model('member_coupon')->count(array('cpns_id'=>$cpnsId,'member_id'=>$memberId,'source'=>1));
        $coupons = app::get('b2c')->model('coupons');
        $cur_coupon = $coupons->dump($cpnsId);
        if($cur_coupon['cpns_max_num'] > 0 ){  //兼容老数据处理老数据还是无限制兑换
            if($cur_coupon_nums >= $cur_coupon['cpns_max_num']){
                $return = [
                    'result' => '您的兑换次数已达上限！',
                    'code' => 5001,
                ];
                return self::return_json($return);
            }
        }

        $obj_point_common = kernel::single('pointprofessional_point_common');
        $real_point_get = $obj_point_common->check_used_point_get($memberId);
        if (!$real_point_get["rs"]){
            $return = [
                'result' => '获取可用积分失败！',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        if($real_point_get['real_point'] < $cur_coupon['cpns_point']){
            $return = [
                'result' => '您的积分不足！',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        if ($oExchangeCoupon->exchange($cpnsId,$memberId,$real_point_get['real_point'],$params)){
            $cpns_point = $params['cpns_point'];
            $member_point = app::get('b2c')->model('member_point');
            if($obj_point_common->point_change_action($memberId,-$cpns_point,$msg,'exchange_coupon',2,$memberId,$memberId,'exchange',false)){
                $change_nums = $cur_coupon['cpns_max_num'] - $cur_coupon_nums -1;
                if($cur_coupon['cpns_max_num'] > 0 ){
                    $return = [
                        'result' => '兑换成功,您还可以兑换'.$change_nums.'张',
                        'code' => 0,
                        'success' => 'true',
                    ];
                }else{
                    $return = [
                        'result' => '兑换成功',
                        'code' => 0,
                        'success' => 'true',
                    ];
                }
                return self::return_json($return);
            }else{

                $oExchangeCoupon->exchange_delete($params);
                $return = [
                    'result' => $msg,
                    'code' => 5001,
                ];
                return self::return_json($return);
            }
        }
        $return = [
            'result' => '积分不足或兑换购物券无效',
            'code' => 5001,
        ];
        return self::return_json($return);
        echo json_encode($arr_json_data);exit;
    }

    //会员中心-兑换优惠券列表
    public function exchangeCouponList(){

        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $return_data = array(
            'coupon_list' => array(),
        );
        $oExchangeCoupon = kernel::single('b2c_coupon_mem');
        
        //验证积分是否用于兑换 
        $site_point_usage = $this->app->getConf('site.point_usage');
        if( $site_point_usage != '1' ){
            return self::return_json($return_data);
        }
        $aExchange = $oExchangeCoupon->get_list();

        if( !$aExchange ){
            return self::return_json($return_data);
        }

        //获取会员等级
        if( !$member['member_lv'] ){
            $memberMdl = app::get('b2c')->model("members");
            $memberInfo = $memberMdl->dump(array('member_id'=>$member['member_id']),'member_lv_id');
            $member['member_lv'] = $memberInfo['member_lv']['member_group_id'];
        }

        foreach ($aExchange as $k => $item) {
            $member_lvs = explode(',',$item['time']['member_lv_ids']);
            if (!in_array($member['member_lv'],(array)$member_lvs)) {
                unset($aExchange[$k]);
                continue;
            }
        }

        $return_data['coupon_list'] = $aExchange;

        return self::return_json($return_data);
    }

    //接口获取退款申请列表
    public function refundlist(){
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            $return = [
                'result' => '请先登录',
                'code' => 5001,
            ];
            return self::return_json($return);
        }

        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $size = isset($_GET['size']) ? $_GET['size'] : 10;
        $nPage =intval($page);

        $mdl_b2c_refund_apply = app::get('b2c')->model('refund_apply');
        $aData = $mdl_b2c_refund_apply->fetchByMember($member['member_id'],$nPage,$size);

        $refund_list = array();
        $totalCount = intval($aData['pager']['total']);

        if( !$aData ){
            $return = [
                'result' => '0',
                'reason' => '',
                'code' => 0,
                'page_total' => ceil($totalCount/$size),
                'page_size' => $size,
                'totalCount' => count($refund_list),
                'pageNum' => $nPage,
                'list' => $refund_list,
            ];
            return self::return_json($return);
        }

        
        //统一获取相关的order_id 获得订单相关信息
        $arr_order_ids = array();
        foreach ($aData["data"] as $var_data){
            $refund_list[$val['order_id']] = $var_data;
            if(!in_array($var_data["order_id"],$arr_order_ids)){
                $arr_order_ids[] = $var_data["order_id"];
            }
        }

        $mdl_b2c_orders = app::get('b2c')->model('orders');
        $rs_orders = $mdl_b2c_orders->getList('*', array("order_id|in"=>$arr_order_ids));
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        foreach ($rs_orders as &$arr_order){
            $arr_order = $mdl_b2c_orders->dump($arr_order['order_id'], '*', $subsdf);
        }
        $orders["data"] = $rs_orders;
       

        $this->get_order_details($orders,'member_orders');
        $oImage = app::get('image')->model('image');
        $oGoods = app::get('b2c')->model('goods');
        $strorager = kernel::single("base_storager");
        $imageDefault = app::get('image')->getConf('image.set');
        foreach($orders['data'] as $k => &$v) {
            $order_payed = kernel::single('b2c_order_pay')->check_payed($v['order_id']);
            if($order_payed==$v['total_amount']){
                $v['is_pay']=1;
            }else{
                $v['is_pay']=0;
            }
            foreach($v['goods_items'] as $k2 => &$v2) {
                $spec_desc_goods = $oGoods->getList('spec_desc',array('goods_id'=>$v2['product']['goods_id']));
                $select_spec_private_value_id = reset($v2['product']['products']['spec_desc']['spec_private_value_id']);
                $spec_desc_goods = reset($spec_desc_goods[0]['spec_desc']);
                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                    $v2['product']['thumbnail_pic'] = $default_product_image;
                }else{
                    if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                        $v2['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                    }
                }
            }
        }

        //做个order_id为key的关系数组
        $rl_order_id_order_info = array();
        foreach ($orders["data"] as $var_order){
            $rl_order_id_order_info[$var_order["order_id"]] = $var_order;
        }
        //压入要order_info用来显示在整体信息下方
        foreach ($aData['data'] as &$var_adata){
            $var_adata["order_info"] = $rl_order_id_order_info[$var_adata["order_id"]];
        }
        unset($var_adata);

        $reasons = $mdl_b2c_refund_apply->get_field_refunds_reason();

        $status_name = array('0'=>'待处理','1'=>'已拒绝','2'=>'已退款');
        
        $refund_list = array();
        foreach($aData['data'] as $aval){

            // if( $aval['order_info']['ship_status'] == 1){
            //     $deliveryModel = app::get('b2c')->model('delivery');
            //     $shipOrder = $deliveryModel->getRow('*', array('order_id'=>$order['order_id']));
            // }

            $goods_items = array();
            foreach($aval['order_info']['goods_items'] as $goods_key=>$goods_val){
                $goods_items[$key] = array(
                    'auditStatus' => 1,
                    'evaluateStatus' => 0, //评价状态
                    'goodsId' => $goods_val['product']['products']['goods_id'],
                    'goodsSkuId' => $goods_val['product']['item_id'],
                    'goodsName' => $goods_val['product']['name'],
                    'orderNo' => $aval['order_id'],
                    'id' => $goods_val['product']['item_id'],
                    'num' => $goods_val['product']['quantity'],
                    'price' => (float)$goods_val['product']['price'],
                    'refundStatus' => 0, //0:正常,1:待审核,2:退款中,3:退款完成
                    'goodsThumLogo' => $strorager->image_path($goods_val['product']['thumbnail_pic'],'m'),
                    'link_url' => $goods_val['product']['link_url'],
                );
            }
            
            $refund_list[] = array(
                'statusName' => $status_name[$aval['status']],
                'auditStatus' => $aval['status'], //0 待处理 1 已拒绝 2 已退款,
                'businessAccount' => '',    //店铺
                'businessId' => '',         //店铺id
                'businessName' => '',       //店铺id
                'createTime' => date('Y-m-d H:i:s',$aval['create_time']),
                'deliverStatus' => $aval['order_info']['ship_status'], //发货状态：0未发货，1已发货，2部分发货，3部分退货，4已退货
                'freight' => (float)$aval['order_info']['shipping']['cost_shipping'], //运费
                'goodsPrices' => number_format($aval['order_info']['total_amount'], 2), //商品总额
                'id' => $aval['order_id'],
                'logisticsCode' => '', //物流公司编码
                'logisticsNo' => '', //物流单号
                'orderItemList' => $goods_items,
                'orderNo' => $aval['order_id'],
                "payStatus" => $aval['order_info']['pay_status'], //是否支付(0 未支付 1 已支付(或拼团成功) 2 处理中 3 部分付款 4 部分退款 5 全额退款) ,6付款成功，拼团没完成,7.拼团退款中,8拼团.等待退款
                "payTradeNo" => '', //支付单号
                "status" => $aval['order_info']['status'], //active:活动, dead:死单, finish:完成, pending:暂停
                "totalPrice" => $aval['order_info']['cur_amount'] //应付总额
            );
        }
        unset($aData,$orders);

        $return = [
            'result' => '0',
            'reason' => '',
            'code' => 0,
            'page_total' => ceil($totalCount/$size),
            'page_size' => $size,
            'totalCount' => count($refund_list),
            'pageNum' => $nPage,
            'list' => $refund_list,
        ];

        // echo "<pre>";var_dump($return);exit;
        return self::return_json($return);
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string tpl
     * @return null
     */
    protected function get_order_details(&$aData,$tml='member_orders')
    {
        if (isset($aData['data']) && $aData['data'])
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }

            foreach ($aData['data'] as &$arr_data_item)
            {
                $this->get_order_detail_item($arr_data_item,$tml);
            }
        }
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string 模版名称
     * @return null
     */
    protected function get_order_detail_item(&$arr_data_item,$tpl='member_order_detail')
    {
        if (isset($arr_data_item) && $arr_data_item)
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }


            $arr_data_item['goods_items'] = array();
            $obj_specification = $this->app->model('specification');
            $obj_spec_values = $this->app->model('spec_values');
            $obj_goods = $this->app->model('goods');
            if (isset($arr_data_item['order_objects']) && $arr_data_item['order_objects'])
            {
                foreach ($arr_data_item['order_objects'] as $k=>$arr_objects)
                {
                    $index = 0;
                    $index_adj = 0;
                    $index_gift = 0;
                    $image_set = app::get('image')->getConf('image.set');
                    if ($arr_objects['obj_type'] == 'goods')
                    {
                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            if (!$arr_items['products'])
                            {
                                $o = $this->app->model('order_items');
                                $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                            }

                            if ($arr_items['item_type'] == 'product')
                            {
                                if ($arr_data_item['goods_items'][$k]['product'])
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k]['product']['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $arr_items['quantity'];

                                $arr_data_item['goods_items'][$k]['product'] = $arr_items;
                                $arr_data_item['goods_items'][$k]['product']['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k]['product']['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k]['product']['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k]['product']['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k]['product']['quantity']);
                                $arr_data_item['goods_items'][$k]['product']['amount'] = $arr_items['amount'];
                                $arr_goods_list = $obj_goods->getList('image_default_id', array('goods_id' => $arr_items['goods_id']));
                                $arr_goods = $arr_goods_list[0];
                                if (!$arr_goods['image_default_id'])
                                {
                                    $arr_goods['image_default_id'] = $image_set['S']['default_image'];
                                }
                                $arr_data_item['goods_items'][$k]['product']['thumbnail_pic'] = $arr_goods['image_default_id'];
                                $arr_data_item['goods_items'][$k]['product']['link_url'] = app::get('site')->router()->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$arr_items['products']['product_id']));
                                if ($arr_items['addon'])
                                {
                                    $arrAddon = $arr_addon = unserialize($arr_items['addon']);
                                    if ($arr_addon['product_attr'])
                                        unset($arr_addon['product_attr']);
                                    $arr_data_item['goods_items'][$k]['product']['minfo'] = $arr_addon;
                                }else{
                                    unset($arrAddon,$arr_addon);
                                }
                                if ($arrAddon['product_attr'])
                                {
                                    foreach ($arrAddon['product_attr'] as $arr_product_attr)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k]['product']['attr']) && $arr_data_item['goods_items'][$k]['product']['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k]['product']['attr'], " ") !== false)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] = substr($arr_data_item['goods_items'][$k]['product']['attr'], 0, strrpos($arr_data_item['goods_items'][$k]['product']['attr'], $this->app->_(" ")));
                                    }
                                }
                            }
                            elseif ($arr_items['item_type'] == 'adjunct')
                            {
                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);


                                if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj])
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $arr_items['quantity'];

                                if (!$arrGoods['image_default_id'])
                                {
                                    $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                }
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj] = $arr_items;
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']);
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['link_url'] = $arrGoods['link_url'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['amount'] = $arr_items['amount'];

                                if ($arr_items['addon'])
                                {
                                    $arr_addon = unserialize($arr_items['addon']);

                                    if ($arr_addon['product_attr'])
                                    {
                                        foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                        }
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")) !== false)
                                    {
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")));
                                    }
                                }

                                $index_adj++;
                            }
                            else
                            {
                                // product gift.
                                if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                                {
                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift])
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift] = $arr_items;
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['name'] = $arr_items['name'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['price'] = $arr_items['price'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity']);
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['link_url'] = $arrGoods['link_url'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'])
                                    {
                                        if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                                $index_gift++;
                            }
                        }
                    }
                    else
                    {
                        if ($arr_objects['obj_type'] == 'gift')
                        {
                            //积分兑换赠品
                            $gift_key = '';
                            if( $arr_objects['obj_alias'] == app::get('b2c')->_('商品区块') ){
                                $gift_key = 'gift';//积分兑换赠品
                            }else{
                                $gift_key = 'order'; //订单送赠品，包含优惠券送赠品
                            }
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {
                                foreach ($arr_objects['order_items'] as $arr_items)
                                {
                                    if (!$arr_items['products'])
                                    {
                                        $o = $this->app->model('order_items');
                                        $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                        $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                                    }

                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if (!isset($arr_items['products']['product_id']) || !$arr_items['products']['product_id'])
                                        $arr_items['products']['product_id'] = $arr_items['goods_id'];

                                    if ($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']])
                                        $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }

                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['name'] = $arr_items['name'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['price'] = $arr_items['price'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['point'] = intval($arr_items['score']*$arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']);
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['nums'] = $arr_items['quantity'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['link_url'] = $arrGoods['link_url'];
                                    $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr']) && $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'])
                                    {
                                        if (strpos($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] = substr($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], 0, strrpos($arr_data_item[$gift_key][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {

                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                $arr_data_item['extends_items'][] = $str_service_goods_type_obj->get_order_object($arr_objects, $arr_Goods,$tpl);
                            }
                        }
                    }
                }
            }

        }
    }


    /**
     * 订单是否售后
     * @param $order_id
     * @param $member_id
     * @return  array=>status 0 不可以售后 1可以售后
     */
    private function __is_order_aftersales($order_id, $member_id)
    {
        $aftersaleStatus = array(
            'status'=>0,
            'status_name'=>'',
            'aftersale_type'=>''
        );
        $order_status = array();
        $order = app::get('b2c')->model('orders');
        $order_status['pay_status'] = array(1,4);
        $order_status['ship_status'] = array(1,2);
        $order_status['received_status'] = 1;
        $order_status['order_id'] = $order_id;
        $order_status['member_id'] = $member_id;
        $order_status['status'] = 'active';
        $aData = $order->getRow('order_id',$order_status);
        $aftersaleType = array(
            1=>'未操作',
            2=>'审核中',
            3=>'接受申请',
            4=>'完成',
            5=>'拒绝',
            6=>'已收货',
            7=>'已质检',
            8=>'补差价',
            9=>'已拒绝退款',
            );
        if($aData){
            //取出已发货的商品
            $deliveryGoods = array();
            $aftersaleGodos = array();
            $deliveryModel = app::get('b2c')->model('delivery');
            $deliveryItemsModel = app::get('b2c')->model('delivery_items');
            $productsModel = app::get('b2c')->model('products');
            $delivery = $deliveryModel->getList('*',array('order_id'=>$order_id,'member_id'=>$member_id,'status'=>'succ'));
            if($delivery){
                foreach ($delivery as $value){
                    $deliveryItemList = $deliveryItemsModel->getList('*',array('delivery_id'=>$value['delivery_id']));
                    if($deliveryItemList){
                        foreach ($deliveryItemList as $val){
                            $deliveryGoods[$val['product_id']]['product_id'] = $val['product_id'];
                            $deliveryGoods[$val['product_id']]['item_type'] = $val['item_type'];
                            $deliveryGoods[$val['product_id']]['number'] = $val['number'];  //发货数量
                        }
                    }
                }
            }
            $aftersaleModel = app::get('aftersales')->model('return_product');
            $aftersaleList = $aftersaleModel->getList('*',array('order_id'=>$order_id));   //'disabled'=>'true' 这个暂时不加，产品售后状态没更新
            if($aftersaleList){
                foreach ($aftersaleList as $aftersaleItem){
                    $product_data = unserialize($aftersaleItem['product_data']);
                    if($product_data){
                        foreach ($product_data as $productGoods){
                            $row = $productsModel ->getRow('*',array('bn'=>$productGoods['bn']));
                            $productGoods['product_id'] = $row['product_id'];
                            array_push($aftersaleGodos, $productGoods);
                            //去除已经售后的商品
                            unset($deliveryGoods[$productGoods['product_id']]);
                        }

                    }
                }
                $aftersaleStatus['status_name'] = $aftersaleType[$aftersaleItem['status']];
                $aftersaleStatus['aftersale_type'] = $aftersaleItem['status'];

                if(empty($deliveryGoods)){
                    //订单商品全部售后
                    $aftersaleStatus['status'] = 0;
                }else{
                    //订单部分商品售后
                    $aftersaleStatus['status'] = 1;
                }
            }else{
                //订单所有商品未售后
                $aftersaleStatus['status'] = 1;
                $aftersaleStatus['status_name'] = '';
                $aftersaleStatus['aftersale_type'] = '';
            }
        }
        return $aftersaleStatus;
    }
    
    private function _process_status(&$order, &$btnStatus)
    {
        $statusName = '';
        //转换订单状态
        switch($order['status']){
            
            case 'dead':
                $statusName = '已关闭';
                break;
                
            case 'finish':
                $statusName = '已完成';
                $btnStatus['aftersale'] = 1;
                break;
                
            default:
                if($order['pay_status']==0){
                    $statusName = '待付款';
                    $btnStatus['cancel'] = 1;
                    $btnStatus['pay'] = 1;
                    
                }elseif($order['pay_status']==4){
                    $statusName = '部分退款';
                    
                }elseif($order['pay_status']==5){
                    $statusName = '已全额退款';
                    
                }elseif($order['pay_status']==6){
                    $statusName = '退款申请中';
                    
                }elseif($order['pay_status']==1 && $order['received_status']==0){
                    switch ($order['ship_status']){
                        case 0:
                            $statusName = '待发货';
                            $btnStatus['refund'] = 1;
                            break;
                        case 1:
                            $statusName = '待收货';
                            $btnStatus['confirm'] = 1;
                            break;
                        case 2:
                            $statusName = '部分发货';
                            break;
                        case 3:
                            $statusName = '部分退货';
                            break;
                        case 4:
                            $statusName = '已退货';
                            break;
                    }                    
                }elseif($order['pay_status']==1 && $order['received_status']==1){
                    $statusName = '已完成';
                }
        }
        
        
        //订单是否包含能售后的商品。全部申请售后的不能再次申请
        if(in_array($order['pay_status'], array(1,2,3,4,6))
            && in_array($order['ship_status'], array(1,2,3))
            && in_array($order['status'], array('active', 'finish'))
            //&& $order['received_status']==0
        ){
            $obj_return_policy = kernel::service("aftersales.return_policy");
            $order['is_afterrec'] = $obj_return_policy->is_order_aftersales($order['order_id']);
            if($order['is_afterrec'])
                $btnStatus['aftersale'] = 1;
        }     

        return $statusName;
    }
    
    
    public function getPayOrderDetail()
    {
        $member = $this->get_current_member();
        if(empty($member['member_id'])){
            return self::api_error('请先登录');
        }
        $member_id = $member['member_id'];
        $order_id = trim($_GET['tradeNo']);
        if( ! $order_id ){
            return self::api_error('订单号错误');
        }

        $objOrder = app::get('b2c')->model('orders');
        $sdf_order = $objOrder->dump($order_id, 'member_id,total_amount,final_amount');
        if( ! $sdf_order){
            return self::api_error('订单不存在');
        }
        
        if($member['member_id']!=$sdf_order['member_id']){
            return self::api_error('没有权限查看该订单');
        }
        
        $res = array(
            'code' =>0,
            'order' =>array(
                'totalFee' => number_format($sdf_order['total_amount'], 2),
            ),
        );
        
        self::return_json($res);
    }
    
}